package com.smile.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.smile.service.config.mqtt.handler.AbstractEventsReplyHandler;
import com.smile.service.entity.device.manager.TopologyOperationResult;
import com.smile.service.entity.response.DeviceConfigResponse;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

@Component
public class DefaultEventsReplyHandler extends AbstractEventsReplyHandler {
    @Override
    public Boolean process(String data,String method, String tid, String bid,String gateway) throws MqttException {
//        System.out.println(data);

        TopologyOperationResult topologyOperationResult = new TopologyOperationResult();
        topologyOperationResult.setResult(0);

        DeviceConfigResponse<TopologyOperationResult> deviceConfigResponse = new DeviceConfigResponse<>();
        deviceConfigResponse.setData(topologyOperationResult);

        deviceConfigResponse.setBid(bid);
        deviceConfigResponse.setTid(tid);
        deviceConfigResponse.setGateway(gateway);
        deviceConfigResponse.setTimestamp(System.currentTimeMillis());
        deviceConfigResponse.setMethod(method);


        //        deviceAppConfig.setNtpServerHost();
//        deviceAppConfig.setNtpServerPort();

        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setRetained(true);
        message.setPayload(JSONObject.toJSONString(deviceConfigResponse).getBytes());
        MqttClient mqttClient = new MqttClient("tcp://120.211.119.131:1883", "feisuan-mqtt-producer-client", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("feisuan");
        connOpts.setPassword("feisuan123456".toCharArray());
        mqttClient.connect(connOpts);

        mqttClient.publish("thing/product/"+gateway+"/events_reply", message);

        return Boolean.TRUE;
    }
}
